﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Drawing.Imaging;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Net;
using System.Data;
using System.Data.OleDb;
using System.Text.RegularExpressions;

namespace MJCOMMEN_CS.Commen_cs
{
    public class Excel_Txt
    {
        //这个方法是指示这个table要哪列，列名怎么修改，就是修改table
        public static DataTable TransformDataTable(DataTable sourceDt, Dictionary<string, string> parsList)
        {
            return OfficeHelper.DataHelper.TransformDataTable(sourceDt, parsList);
        }
        public static void ToExcel(System.Web.HttpResponse response, string filename, DataTable Dt)
        {
            try
            {
                OfficeHelper.ExcelHelper.Output(response, filename, Dt);
            }
            catch { }
        }
        /// <summary>
        /// 导出excel
        /// </summary>
        /// <param name="filename">放文件的路径和名称</param>
        /// <param name="Dt">经过处理后的table，就是上面</param>
        /// <returns></returns>
        public static bool ToExcel(string filename, DataTable Dt)
        {
            try
            {
                return OfficeHelper.ExcelHelper.Output(filename, Dt);
            }
            catch { return false; }
        }
    }
    public class WebCommon
    {
        public static string Bytes2Hex(byte[] bytes)
        {
            string lin = "0123456789abcdef";
            string str = "";
            foreach (byte b in bytes)
            {
                str += lin[b >> 4];
                str += lin[b & 0x0f];
            }
            return str;
        }

        /// <summary>
        /// MD5 加密静态方法
        /// </summary>
        /// <param name="EncryptString">待加密的密文</param>
        /// <returns>returns</returns>
        public static string MD5Encrypt(string EncryptString)
        {
            MD5 m_ClassMD5 = new MD5CryptoServiceProvider();

            try
            {
                return Bytes2Hex(m_ClassMD5.ComputeHash(Encoding.Default.GetBytes(EncryptString)));
            }
            catch { return null; }
            finally { m_ClassMD5.Clear(); }
        }

        #region  des3
        static byte[] keyiv = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
        static byte[] key = Convert.FromBase64String("YWJjZGVmZ2hpjktsbW5vcHFyc3R1dnd4");

        public static string CBCDecode(string data)
        {
            try
            {
                data = data.Replace(" ", "+");
                System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
                byte[] ss = Convert.FromBase64String(data);
                byte[] s = Des3DecodeCBC(key, keyiv, ss);
                string d = utf8.GetString(s).Trim();
                d = d.Replace("\0", "");
                return d;
            }
            catch
            {
                return "error";
            }
        }

        public static string CBCEncode(string data)
        {
            try
            {
                System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
                byte[] ss = utf8.GetBytes(data);
                byte[] s = Des3EncodeCBC(key, keyiv, ss);
                string d = Convert.ToBase64String(s);
                return d;
            }
            catch (Exception err)
            {
                WebCommon.Log("秘文解密出错" + err.Message);
                return data;
            }
        }
        public static byte[] Des3EncodeCBC(byte[] key, byte[] iv, byte[] data)
        {
            try
            {
                MemoryStream mStream = new MemoryStream();
                TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider();
                tdsp.Mode = CipherMode.CBC;             //默认值
                tdsp.Padding = PaddingMode.PKCS7;       //默认值
                CryptoStream cStream = new CryptoStream(mStream, tdsp.CreateEncryptor(key, iv), CryptoStreamMode.Write);
                cStream.Write(data, 0, data.Length);
                cStream.FlushFinalBlock();
                byte[] ret = mStream.ToArray();
                cStream.Close();
                mStream.Close();
                return ret;
            }
            catch
            {
                return data;
            }
        }

        public static byte[] Des3DecodeCBC(byte[] key, byte[] iv, byte[] data)
        {
            try
            {
                MemoryStream msDecrypt = new MemoryStream(data);
                TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider();

                tdsp.Mode = CipherMode.CBC;
                tdsp.Padding = PaddingMode.PKCS7;
                CryptoStream csDecrypt = new CryptoStream(msDecrypt, tdsp.CreateDecryptor(key, iv), CryptoStreamMode.Read);

                byte[] fromEncrypt = new byte[data.Length];
                csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
                return fromEncrypt;

            }
            catch
            {
                return data;

            }
        }
        #endregion

        #region Alert
        /// <summary>
        /// JavaScript pop-up small window
        /// </summary>
        /// <param name="js"> window's Information</param>
        public static void Alert(string message)
        {
            #region
            string js = @"<Script language='JavaScript'>
                    alert('" + message + "');</Script>";
            HttpContext.Current.Response.Write(js);
            #endregion
        }

        /// <summary>
        /// JavaScript pop-up small window
        /// </summary>
        /// <param name="js"> window's Information</param>
        public static void Alert(Page page, string message)
        {
            #region
            string js = @"<Script language='JavaScript'>
                    alert('" + message + "');</Script>";
            page.ClientScript.RegisterStartupScript(page.GetType(), "alert", js);
            #endregion
        }
        public static void Alert(Page page, string message, string url)
        {
            #region
            if (url.Contains("?"))
            {
                url += "&random=" + new Random().NextDouble().ToString();
            }
            else
            {
                url += "?random=" + new Random().NextDouble().ToString();
            }
            string js = @"<Script language='JavaScript'>
                    alert('" + message + "');location.href='" + url + "'</Script>";
            if (url.ToLower().Contains("login.html"))
            {
                js = @"<Script language='JavaScript'>
                    alert('" + message + "');top.location.href='" + url + "'</Script>";
            }
            page.ClientScript.RegisterStartupScript(page.GetType(), "alert", js);
            #endregion
        }
        public static void Alert2(Page page, string message, string url)
        {
            #region
            if (url.Contains("?"))
            {
                url += "&random=" + new Random().NextDouble().ToString();
            }
            else
            {
                url += "?random=" + new Random().NextDouble().ToString();
            }
            string js = @"<Script language='JavaScript'>
                    alert('" + message + "');parent.tb_remove();parent.location.href='" + url + "'</Script>";
            if (url.ToLower().Contains("login.html"))
            {
                js = @"<Script language='JavaScript'>
                    alert('" + message + "');top.location.href='" + url + "'</Script>";
            }
            page.ClientScript.RegisterStartupScript(page.GetType(), "alert", js);
            #endregion
        }

        #endregion

        public static void redireurl(Page page, string url)
        {
            #region
            if (url.Contains("?"))
            {
                url += "&random=" + new Random().NextDouble().ToString();
            }
            else
            {
                url += "?random=" + new Random().NextDouble().ToString();
            }
            string js = @"<Script language='JavaScript'>
                  location.href='" + url + "'</Script>";
            if (url.ToLower().Contains("login.html"))
            {
                js = @"<Script language='JavaScript'>
                    top.location.href='" + url + "'</Script>";
            }
            page.ClientScript.RegisterStartupScript(page.GetType(), "", js);
            #endregion
        }
        public static void gotoUrl(Page page, string url, string titlename)
        {
            #region
            string js = @"<Script language='JavaScript'>
                  showpage2('" + url + "','" + titlename + "');</Script>";
            page.ClientScript.RegisterStartupScript(page.GetType(), "", js);
            #endregion
        }


        /// 记录日志至文本文件 /// /// 记录的内容 
        public static void Log(string Path, string message)
        {
            try
            {
                //新建文件夹
                if (!Directory.Exists(Path))
                {
                    Directory.CreateDirectory(Path);
                }
                string FILE_NAME = Path + "/" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
                if (!File.Exists(FILE_NAME))
                {
                    StreamWriter sr = File.CreateText(FILE_NAME);
                    sr.Close();
                }

                using (StreamWriter sr = File.AppendText(FILE_NAME))
                {
                    lock (sr)
                    {
                        sr.WriteLine("\n");
                        sr.WriteLine(DateTime.Now.ToString() + ":" + message);
                        sr.Close();
                    }
                }
            }
            catch { }
        }
        /// 记录日志至文本文件 /// /// 记录的内容 
        public static void Log(string message)
        {
            try
            {
                string Path = HttpContext.Current.Server.MapPath("~/Logs/") + DateTime.Now.ToString("yyyyMM");
                //新建文件夹
                if (!Directory.Exists(Path))
                {
                    Directory.CreateDirectory(Path);
                }
                string FILE_NAME = Path + "/" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
                if (!File.Exists(FILE_NAME))
                {
                    StreamWriter sr = File.CreateText(FILE_NAME);
                    sr.Close();
                }

                using (StreamWriter sr = File.AppendText(FILE_NAME))
                {
                    lock (sr)
                    {
                        sr.WriteLine("\n");
                        sr.WriteLine(DateTime.Now.ToString() + ":" + message);
                        sr.Close();
                    }
                }
            }
            catch { }
        }

      
        //获取当前接口路径
        public static string Url
        {
            get
            {
                if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("member/handler.ashx"))
                {
                    string url = HttpContext.Current.Request.Url.ToString().ToLower();
                    int len = url.IndexOf("member/handler.ashx");
                    url = url.Substring(0, len - 1);
                    return url;
                }
                else
                {
                    if (HttpContext.Current.Request.Url.Port == 80)
                        return "http://" + HttpContext.Current.Request.Url.Host;
                    else
                        return "http://" + HttpContext.Current.Request.Url.Host + ":" + HttpContext.Current.Request.Url.Port;
                }
            }
        }
        public static void CloseWindow(Page page)
        {
            string js = @"<Script language='JavaScript'>parent.tb_remove();</Script>";
            page.ClientScript.RegisterStartupScript(page.GetType(), "alert", js);
        }
        public static void CloseWindow(Page page, string url)
        {
            if (url.Contains("?"))
            {
                url += "&random=" + new Random().NextDouble().ToString();
            }
            else
            {
                url += "?random=" + new Random().NextDouble().ToString();
            }
            string js = @"<Script language='JavaScript'>parent.tb_remove();parent.location.href='" + url + "'</Script>";
            page.ClientScript.RegisterStartupScript(page.GetType(), "alert", js);
        }
        /// <summary>
        /// 删除文件夹创建时间或修改时间的30分钟前的文件
        /// </summary>
        /// <param name="path"></param>
        public static void DeleteFiles(string path)
        {
            try
            {
                //DirectoryInfo操作对于文件夹，FileInfo操作对于文件
                DirectoryInfo dir = new DirectoryInfo(path);
                foreach (FileInfo fi in dir.GetFiles("*"))
                {
                    if (fi.CreationTime < DateTime.Now.AddMinutes(-30) || fi.LastWriteTime < DateTime.Now.AddMinutes(-30))
                    {
                        fi.Delete();//删除冗余的图片
                    }
                }
            }
            catch { }
        }

        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <returns></returns>
        public static string CreateFiles(string paths)
        {
            string path = HttpContext.Current.Server.MapPath(paths);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            return path;
        }


        /// <summary>
        /// 无损压缩图片
        /// </summary>
        /// <param name="sFile">原图片</param>
        /// <param name="dFile">压缩后保存位置</param>
        /// <param name="dHeight">高度</param>
        /// <param name="dWidth">宽度</param>
        /// <param name="flag">压缩质量 1-100</param>
        /// <returns></returns>
        public static bool CompressImage(string sFile, string dFile, int dHeight, int dWidth, int flag)
        {

            System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
            ImageFormat tFormat = iSource.RawFormat;
            int sW = 0, sH = 0;
            //按比例缩放
            Size tem_size = new Size(iSource.Width, iSource.Height);

            if (tem_size.Width > dHeight || tem_size.Width > dWidth)
            {
                if ((tem_size.Width * dHeight) > (tem_size.Height * dWidth))
                {
                    sW = dWidth;
                    sH = (dWidth * tem_size.Height) / tem_size.Width;
                }
                else
                {
                    sH = dHeight;
                    sW = (tem_size.Width * dHeight) / tem_size.Height;
                }
            }
            else
            {
                sW = tem_size.Width;
                sH = tem_size.Height;
            }
            Bitmap ob = new Bitmap(dWidth, dHeight);
            Graphics g = Graphics.FromImage(ob);
            g.Clear(Color.WhiteSmoke);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
            g.Dispose();
            //以下代码为保存图片时，设置压缩质量
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;
            try
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    // if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
                }
                else
                {
                    ob.Save(dFile, tFormat);
                }
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                iSource.Dispose();
                ob.Dispose();
                File.Delete(sFile);
            }

        }

        public static string PostWebRequest(string str, string loginUrl)//成功返回pass，失败返回fail   
        {
            try
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(str); // 转化          
                HttpWebRequest webRequest2 = (HttpWebRequest)WebRequest.Create(loginUrl);
                CookieContainer cc = new CookieContainer();
                webRequest2.CookieContainer = cc;
                webRequest2.Timeout = 200000;
                webRequest2.Method = "POST";
                webRequest2.ContentType = "application/x-www-form-urlencoded";
                webRequest2.ContentLength = byteArray.Length;
                Stream newStream = webRequest2.GetRequestStream();
                // Send the data.
                newStream.Write(byteArray, 0, byteArray.Length);    //写入参数
                newStream.Close();
                HttpWebResponse response2 = (HttpWebResponse)webRequest2.GetResponse();
                StreamReader sr2 = new StreamReader(response2.GetResponseStream(), Encoding.Default);
                string text2 = sr2.ReadToEnd();
                newStream.Close();
                sr2.Close();
                response2.Close();
                webRequest2.Abort();
                return text2;
            }
            catch
            {
                return "通过IP查询详细地址出错！";
            }
        }
      
        public static string GetReplaceText(string p)
        {
            p = p.Trim();
            Regex reg = new Regex("select", RegexOptions.IgnoreCase);
            p = reg.Replace(p, "");
            reg = new Regex("update", RegexOptions.IgnoreCase);
            p = reg.Replace(p, "");
            reg = new Regex("insert", RegexOptions.IgnoreCase);
            p = reg.Replace(p, "");
            reg = new Regex("delete", RegexOptions.IgnoreCase);
            p = reg.Replace(p, "");
            reg = new Regex("--", RegexOptions.IgnoreCase);
            p = reg.Replace(p, "");
            return p;
        }
    }
}
